//
//  WBNetworkManager.swift
//  ZWWEIBO
//
//  Created by xzw on 2018/4/5.
//  Copyright © 2018年 xzw. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMothod {
    
    case GET
    case POST
}

class WBNetworkManager: AFHTTPSessionManager {

    //单例
    static let sharedInstance: WBNetworkManager = {
        
        let sharedIns = WBNetworkManager()
        
        //设置服务器返回数据反序列化支持的格式
        sharedIns.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return sharedIns
    }()

    
    //用户登录模型
    lazy var userModel : WBUserModel = WBUserModel()
    
    
    var userLogin : Bool {
        return userModel.access_token != nil
    }

    
    /// 带登录令牌的网络请求
    ///
    /// - Parameters:
    ///   - mothod: get/post
    ///   - URLString: url
    ///   - parameters: parameters
    ///   - completed: response返回结果，isSuccessed请求成功与失败
    func requestWithAccessToken(mothod: HTTPMothod = .GET,URLString: String,parameters: [String:Any]?,completed:@escaping ((_ response: Any?,_ isSuccessed: Bool)->())){
        
        //1.判断access_token有没有值
        if userModel.access_token == nil {
            print("access_token为空，需要登录")
            //登录
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            
            completed(nil, false)
            return
        }
        
        //2.拼接令牌参数
        var parameters = parameters
        if parameters == nil {
            //实例化字典
            parameters = [String:Any]()
        }
        parameters!["access_token"] = userModel.access_token
        
        //3.调用网络请求
       request(mothod: mothod, URLString: URLString, parameters: parameters, completed: completed)
    }
    
    
    /// 用一个方法封装get/post请求
    ///
    /// - Parameters:
    ///   - mothod: get/post
    ///   - URLString: url
    ///   - parameters:parameters
    ///   - completed:response返回结果，isSuccessed请求成功与失败
    func request(mothod: HTTPMothod = .GET,URLString: String,parameters:[String:Any]?,completed:@escaping ((_ response: Any?,_ isSuccessed: Bool)->())){
        
        //请求成功
        let success = {(task:URLSessionDataTask,response:Any?) -> () in
            completed(response,true)
        }
        
        //请求失败
        let failure = {(task:URLSessionDataTask?,error:Error)->() in
           
            //处理令牌失效问题403
            //对于测试用户(应用程序还没有提交给新浪微博审核)每天刷新量是有限的
            //超出上限，token会被锁定一段时间
            //解决办法，新建一个应用，重新获取token
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("登陆令牌过期了")
                
                //登录
                 NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad token")
            }
            print("网络请求错误 \(error)")
            completed(nil,false)
        }
        
        //Get请求
        if mothod == .GET {
             get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }else //Post请求
        {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
}
